package edu.zhangxu.util;

import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtils {
    private static DataSource dataSource;

    static {
        try {
            InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");
            Properties pros = new Properties();
            pros.load(in);
            dataSource = BasicDataSourceFactory.createDataSource(pros);
            if(in != null) {
                in.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static Connection getConnection() throws Exception {
        return dataSource.getConnection();
    }

    public static void closeConnection(Connection con, Statement ps) {
        try {
            if(ps != null) ps.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            if(con != null) con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void closeConnection(Connection con, Statement ps, ResultSet rs) {
        try {
            if(rs != null) rs.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            if(ps != null) ps.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            if(con != null) con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
